<?php

namespace frontend\modules\shop\controllers;

use Yii;
use frontend\components\Controller;
use common\models\shop\ShopOrder;
use frontend\modules\shop\models\PlaceOrderForm;

/**
 * 订单相关
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class OrderController extends Controller {

    /**
     * @inheritdoc
     */
    public $modelClass = 'frontend\modules\shop\models\OrderSearch';

    /**
     * Declares the allowed HTTP verbs.
     * Please refer to [[VerbFilter::actions]] on how to declare the allowed verbs.
     * @return array the allowed HTTP verbs.
     */
    protected function verbs() {
        return [
            'index' => ['GET'],
            'view' => ['GET'],
            '*' => ['POST'],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions() {
        return [
            'view' => [
                'class' => 'yii\rest\ViewAction',
                'modelClass' => 'frontend\modules\shop\models\OrderView'
            ],
        ];
    }

    /**
     * 订单列表
     * @return mixed
     */
    public function actionIndex() {
        /* @var $modelClass \frontend\modules\shop\models\OrderSearch */
        $modelClass = new $this->modelClass;
        $modelClass->user_id = $this->uid;
        return $modelClass->search(Yii::$app->request->getQueryParams());
    }

    /**
     * 统一下单
     * @return mixed
     */
    public function actionCreate() {
        $model = new PlaceOrderForm();
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('订单创建失败');
        }
        return $model->save();
    }

    /**
     * 取消订单
     * @return mixed
     */
    public function actionCancel() {
        $id = Yii::$app->request->post('id');
        $msg = '订单操作成功';
        $status = ShopOrder::cancel([
            'id' => $id,
            'user_id' => $this->uid,
        ], $msg);
        return compact('status', 'msg');
    }

    /**
     * 统一下单
     * @return mixed
     */
    public function actionConfirm() {
        $id = Yii::$app->request->post('id');
        $model = ShopOrder::findOrFail([
            'id' => $id,
            'user_id' => $this->uid,
        ]);
        $model->status = ShopOrder::STATUS_COMPLETE;
        return $model->save();
    }

}
